package com.qing.administer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qing.administer.entity.SysMenu;
import com.qing.administer.mapper.SysMenuMapper;
import com.qing.administer.pojo.vo.SysMenuVO;
import com.qing.administer.pojo.vo.TreeVO;
import com.qing.administer.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author qing
 * @since 2021-09-17
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

	@Autowired
	private SysMenuMapper sysMenuMapper;

	@Override
	public Page<SysMenu> findPage(Long current, Long size, Integer status, String keyword) {
		Page<SysMenu> page=new Page<>(current,size);
		QueryWrapper<SysMenu> queryWrapper=new QueryWrapper<>();
		if(StringUtils.hasLength(keyword)){
			queryWrapper.likeRight("name",keyword);
		}
		return sysMenuMapper.selectPage(page,queryWrapper);

	}

	@Override
	public List<SysMenu> selectSysMenuByRoleId(Long roleId) {
		return sysMenuMapper.selectSysMenuByRoleId(roleId);
	}


	@Override
	public List<TreeVO> findMenuTree() {
		List<SysMenu> sysMenuList=sysMenuMapper.selectList(new QueryWrapper<>());
		return  sysMenuList.stream().filter(item->item.getParentId().equals(0L)).map(item->getTreeVo(item,sysMenuList)).collect(Collectors.toList());
	}


	@Override
	public List<SysMenuVO> findSysMenu() {
		List<SysMenu> sysMenuList=sysMenuMapper.selectList(new QueryWrapper<>());
		return  sysMenuList.stream().filter(item->item.getParentId().equals(0L)).map(item->getSysMenuVO(item,sysMenuList)).collect(Collectors.toList());
	}



	private TreeVO getTreeVo(SysMenu sysMenu,List<SysMenu>  sysMenus){
		return  new TreeVO(sysMenu.getMenuId(),sysMenu.getName(),true,getTreeChildren(sysMenus,sysMenu.getMenuId()));
	}

	private List<TreeVO> getTreeChildren(List<SysMenu> sysMenus,Long menuId){
		return  sysMenus.stream().filter(item->item.getParentId().equals(menuId)).map(item->getTreeVo(item,sysMenus)).collect(Collectors.toList());
	}



	private SysMenuVO getSysMenuVO(SysMenu sysMenu,List<SysMenu>  sysMenus){
		SysMenuVO sysMenuVO=new SysMenuVO();
		BeanUtils.copyProperties(sysMenu,sysMenuVO);
		sysMenuVO.setChildren(getSysMenuChildren(sysMenus,sysMenu.getMenuId()));
		return sysMenuVO;
	}

	private List<SysMenuVO> getSysMenuChildren(List<SysMenu> sysMenus,Long menuId){
		return  sysMenus.stream().filter(item->item.getParentId().equals(menuId)).map(item->getSysMenuVO(item,sysMenus)).collect(Collectors.toList());
	}
}
